import 'package:get/get.dart';
import '../../../hj_model/home/home_tabs_entity.dart';
import '../../../hj_model/home/module_detail_model.dart';
import '../../../hj_utils/api_service/vid_service.dart';
import '../../../tools_base/ad_insert_manager.dart';
import '../../../tools_base/debug_log.dart';
import '../../../tools_base/global_store/local_ads_info_store.dart';
import 'home_tab_base_logic.dart';

const Interval = 4;

class HomeTabSortLogic extends HomeTabBaseLogic {
  HomeTabSortLogic(int index, ModuleData tabModel, {bool isDarkStyle = false})
      : super(index, tabModel, isDarkStyle: isDarkStyle);

  List<String> get sortTitles => ['热门推荐', '最新上架', '最多观看', '最多收藏'];

  List<int> get sortParam => [2, 1, 3, 7];
  int moduleSort = 2; // 1: 最新发布  2:本月最热 3:最多观看 7:最多收藏

  RxBool isGridStyle = true.obs; // type=1 展示切换样式
  RxBool isSortMenuInTop = false.obs;

  bool get isNewestStyle => false; //tabModel.showType == 1;

  void initData() async {
    isLoadingData = true;
    update();
    _loadData(sortValue: moduleSort);
  }

  @override
  void onReady() {
    initData();
    super.onReady();
  }

  void sortMenuEvent(int value) {
    moduleSort = sortParam[value];
    isLoadingData = true;
    update();
    _loadData(sortValue: moduleSort);
  }

  void onTooleAction() {
    isGridStyle.value = !isGridStyle.value;
    update();
  }

  void refreshData() {
    _loadData(sortValue: moduleSort);
  }

  void loadMoreData() {
    _loadData(page: currentPage + 1, sortValue: moduleSort);
  }

  void _loadData({int page = 1, int size = 20, int sortValue = 0}) async {
    try {
      ModuleDetailModel? retResp =
          await VidService.getModuleDetail(tabModel.id ?? '', moduleSort: sortValue, pageNumber: page, pageSize: size);

      currentPage = page;
      if (currentPage == 1) {
        dataSource = retResp;
      } else {
        dataSource?.allVideoInfo?.addAll(retResp?.allVideoInfo ?? []);
        dataSource?.allMediaInfo?.addAll(retResp?.allMediaInfo ?? []);
        dataSource?.allSection?.addAll(retResp?.allSection ?? []);
      }
      dataSource?.allVideoInfo?.removeWhere((element) => element.isRandomAd());
      if(!isNewestStyle) {
        AdInsertManager.video(dataSource?.allVideoInfo ?? [], getAdvByTypeSync(11), adGap: 6);
      }
      if (retResp?.hasNext == true) {
        refreshController?.loadComplete();
      } else {
        refreshController?.loadNoData();
      }
    } catch (e) {
      debugLog(e);
      refreshController?.loadComplete();
    }
    refreshController?.refreshCompleted();
    isLoadingData = false;
    update();
  }
}
